using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using BCWAccountVip;
using I2.Loc;
using UnityEngine;
using com.amazon.device.iap.cpt;

public class InAppShop : MonoBehaviour
{
	private struct InAppCurrency
	{
		public float price;

		public string code;
	}

	private const int ConsuneFailureCountMax = 8;

	public static InAppShop instance;

	public List<iapInfo> starterPackIAPs_iOS = new List<iapInfo>();

	public List<iapInfo> starterPackIAPs_Android = new List<iapInfo>();

	[SerializeField]
	private List<iapInfo> accountVipIAPs_iOS = new List<iapInfo>();

	[SerializeField]
	private List<iapInfo> accountVipIAPs_Android = new List<iapInfo>();

	[SerializeField]
	private List<int> accountVipDays = new List<int>();

	private List<string> arrKeyProducts = new List<string>();

	private bool internetEnabled;

	private string[] _products;

	private GooglePurchase _savedPurchase;

	private HashSet<string> _productsToConsume = new HashSet<string>();

	private int _consumeFailureCount;

	private string purchaseProductPayload;

	private Dictionary<string, InAppCurrency> dictProductCurrency = new Dictionary<string, InAppCurrency>();

	public static GamerType currentGamerType
	{
		get
		{
			float num = BCWStorage.Get<float>("Donated_Money");
			if (num <= 0f)
			{
				return GamerType.NonPaying;
			}
			if (num > 0f && num < 5f)
			{
				return GamerType.Hobo;
			}
			if (num >= 5f && num < 20f)
			{
				return GamerType.Gudgeon;
			}
			if (num >= 20f && num < 40f)
			{
				return GamerType.Dolphin;
			}
			if (num >= 40f)
			{
				return GamerType.Whale;
			}
			return GamerType.NonPaying;
		}
	}

	public static event Action eventBuyAccount;

	public void Init()
	{
		if (InAppShopUI.instance != null)
		{
			foreach (InAppProduct listProduct in InAppShopUI.instance.listProducts)
			{
				listProduct.setRuleIdPlatform();
			}
		}
		InitShop();
		if (InAppShopUI.instance != null)
		{
			InAppShopUI.instance.GetComponentsInChildren<SortShopGrid>().ToList().ForEach(delegate(SortShopGrid x)
			{
				x.SortGrid();
			});
		}
		GoogleIAB.init("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqsXnLbQdmJI/MvDCtO+Z6/uvUMDfjFzlMfRE5O2o53p4QMEBSmKs3T9OW/5tta2BMHMlt4f2r6uj7KJYh93lgdkSjDMSDsk+ryG6865wsSukASUQamzXS0VFZjBwLqK9qTW6TS8KdeMLNGxQmgK4WQqV0+b+oW4n2T6UoCnX7JQegeCgtEt0mrg0cPk4kW1bfPKr11V2lPfnjBepUIpX9GSoPGXuYPAHVfxVDp0d9N3fhv8eLjhVMvM3kpr4hYD4gWxBkOQDkZ+m2jJFi/zdUehKyTqLvwm4PAPL1wL3GAkb3dfAh3ZgeflQ2ZbB8JEDy3/QK+4aveV/DbRPVTFVVwIDAQAB");
		GoogleIAB.setAutoVerifySignatures(true);
		RefreshProducts();
	}

	private void Awake()
	{
		instance = this;
		UnityEngine.Object.DontDestroyOnLoad(this);
		Subscribe();
	}

	private void OnDestroy()
	{
		Unsubscribe();
		instance = null;
	}

	private void Subscribe()
	{
		GoogleIABManager.billingSupportedEvent += billingSupportedEvent;
		GoogleIABManager.billingNotSupportedEvent += billingNotSupportedEvent;
		GoogleIABManager.queryInventorySucceededEvent += queryInventorySucceededEvent;
		GoogleIABManager.queryInventoryFailedEvent += queryInventoryFailedEvent;
		GoogleIABManager.purchaseCompleteAwaitingVerificationEvent += purchaseCompleteAwaitingVerificationEvent;
		GoogleIABManager.purchaseSucceededEvent += purchaseSucceededEvent;
		GoogleIABManager.purchaseFailedEvent += purchaseFailedEvent;
		GoogleIABManager.consumePurchaseSucceededEvent += consumePurchaseSucceededEvent;
		GoogleIABManager.consumePurchaseFailedEvent += consumePurchaseFailedEvent;
		RefreshProducts();
	}

	private void Unsubscribe()
	{
		GoogleIABManager.billingSupportedEvent -= billingSupportedEvent;
		GoogleIABManager.billingNotSupportedEvent -= billingNotSupportedEvent;
		GoogleIABManager.queryInventorySucceededEvent -= queryInventorySucceededEvent;
		GoogleIABManager.queryInventoryFailedEvent -= queryInventoryFailedEvent;
		GoogleIABManager.purchaseCompleteAwaitingVerificationEvent += purchaseCompleteAwaitingVerificationEvent;
		GoogleIABManager.purchaseSucceededEvent -= purchaseSucceededEvent;
		GoogleIABManager.purchaseFailedEvent -= purchaseFailedEvent;
		GoogleIABManager.consumePurchaseSucceededEvent -= consumePurchaseSucceededEvent;
		GoogleIABManager.consumePurchaseFailedEvent -= consumePurchaseFailedEvent;
	}

	private void OnEnable()
	{
		RefreshProducts();
	}

	private void Start()
	{
		Init();
	}

	public void buyProductCoinsWithID(string idProduct)
	{
		if (InAppShopUI.instance != null)
		{
			InAppShopUI.instance.blockPanel.gameObject.SetActive(true);
		}
		string text = null;
		foreach (InAppProduct listProduct in InAppShopUI.instance.listProducts)
		{
			if (listProduct.idItems == idProduct)
			{
				text = _products[listProduct.nomProduct];
			}
		}
		if (text != null)
		{
			BCWDebug.Log("preparing to purchase product: " + text);
			purchaseProductPayload = Time.smoothDeltaTime.ToString() + UnityEngine.Random.Range(9999f, 100000000f);
			GoogleIAB.purchaseProduct(idProduct, purchaseProductPayload);
			ActivityIndicator.activEnabled = true;
			RefreshProducts();
		}
		else
		{
			BCWDebug.Log("error idProduct");
		}
	}

	public void BuyIap(string iapID)
	{
		string text = null;
		BCWDebug.Log("preparing to purchase product: " + text);
		purchaseProductPayload = Time.smoothDeltaTime.ToString() + UnityEngine.Random.Range(9999f, 100000000f);
		GoogleIAB.purchaseProduct(iapID, purchaseProductPayload);
	}

	public void RefreshProducts()
	{
		if (InAppShopUI.instance == null)
		{
			return;
		}
		foreach (InAppProduct listProduct in InAppShopUI.instance.listProducts)
		{
			listProduct.reset();
		}
		if (InAppShopUI.instance != null)
		{
			BCWDebug.LogError("InAppShopUI.instance not a null", "TESTING");
		}
		if (ActivityIndicator.activEnabled)
		{
			return;
		}
		internetEnabled = settings.isConnected;
		if (_products == null)
		{
			BCWDebug.Log("error _products");
		}
		if (_products == null)
		{
			return;
		}
		BCWDebug.LogError("Product is not a null  Length  " + _products.Length, "TESTING");
		int i;
		for (i = 0; i < _products.Length; i++)
		{
			InAppProduct inAppProduct = InAppShopUI.instance.listProducts.Find((InAppProduct p) => p.idItems.Equals(_products[i]));
			if (inAppProduct != null)
			{
				BCWDebug.LogError("find product is not a null", "TESTING");
			}
			else
			{
				BCWDebug.LogError("Product null", "TESTING");
			}
			if (!(inAppProduct == null))
			{
				inAppProduct.productEnabled = true;
				internetEnabled = true;
				inAppProduct.nomProduct = i;
				inAppProduct.vklBut();
			}
		}
	}

	public float GetIAPCost(string iapID)
	{
		List<iapInfo> list = new List<iapInfo>();
		if (Application.platform == RuntimePlatform.OSXEditor)
		{
			list.AddRange(starterPackIAPs_iOS);
			list.AddRange(accountVipIAPs_iOS);
		}
		else if (Application.platform == RuntimePlatform.IPhonePlayer)
		{
			list.AddRange(starterPackIAPs_iOS);
			list.AddRange(accountVipIAPs_iOS);
		}
		else if (Application.platform == RuntimePlatform.Android)
		{
			list.AddRange(starterPackIAPs_Android);
			list.AddRange(accountVipIAPs_Android);
		}
		foreach (iapInfo item in list)
		{
			if (item.id == iapID)
			{
				return item.cost;
			}
		}
		if (InAppShopUI.instance != null)
		{
			InAppProduct inAppProduct = InAppShopUI.instance.listProducts.Find((InAppProduct p) => p.idItems.Equals(iapID));
			if (inAppProduct != null)
			{
				return inAppProduct.dollarPrice;
			}
		}
		return 0f;
	}

	private void UpdateGamerType(string idProduct)
	{
		BCWStorage.Set("Donated_Money", BCWStorage.Get<float>("Donated_Money") + GetIAPCost(idProduct), true);
	}

	public void productWithIdBuySuccessful(string idProduct, string token = "")
	{
		BCWDebug.Log("idProduct: " + idProduct, "InApp");
		if (InAppShopUI.instance != null)
		{
			InAppShopUI.instance.blockPanel.SetActive(false);
		}
		if (InAppShopUI.instance != null)
		{
			InAppShopUI.instance.promoRewardCotrollerUI.ClearRewards();
		}
		if (starterPackIAPs_iOS.Select((iapInfo x) => x.id).Contains(idProduct) || starterPackIAPs_Android.Select((iapInfo x) => x.id).Contains(idProduct))
		{
			BCWDebug.Log("idProduct contains in starterPackIAPs", "InApp");
			StarterPacksManager.instance.SucessfulPurchaseStarterPackIAP(idProduct);
			UpdateGamerType(idProduct);
		}
		else if (accountVipIAPs_iOS.Select((iapInfo x) => x.id).Contains(idProduct) || accountVipIAPs_Android.Select((iapInfo x) => x.id).Contains(idProduct))
		{
			BCWDebug.Log("idProduct contains in accountVipIAPs", "InApp");
			Dictionary<string, ManagerVip.ConfigVip> configVips = ManagerVip.GetInstance().ConfigVips;
			if (configVips.ContainsKey(idProduct) && ManagerVip.GetInstance().AddDays(configVips[idProduct].countDays))
			{
				BCWDebug.Log("account vip add days succsesful", "InApp");
				if (InAppShop.eventBuyAccount != null)
				{
					InAppShop.eventBuyAccount();
				}
			}
			UpdateGamerType(idProduct);
		}
		else if (InAppShopUI.instance != null)
		{
			BCWDebug.Log("listProducts.Count: " + InAppShopUI.instance.listProducts.ToString(), "InApp");
			InAppProduct inAppProduct = InAppShopUI.instance.listProducts.Find((InAppProduct p) => p.idItems.Equals(idProduct));
			if (BCWDebug.isDebugBuild)
			{
				BCWDebug.Log("buy product shop coins with id = " + idProduct, "InApp");
			}
			inAppProduct.InitMoneyCount();
			if (inAppProduct.isSubscription)
			{
				InAppSubscriptionsController.instance.StartSubscription();
				InAppSubscriptionsController.SubscriptionParameters promoParameters = InAppSubscriptionsController.instance.PromoParameters;
				if (promoParameters.startCash > 0)
				{
					CoroutineRunner.Instance.StartCoroutine(settings.ShowSpecialLabelWithAnimationDelayd(promoParameters.startCash, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("cash", promoParameters.startCash), false));
				}
				if (promoParameters.startGold > 0)
				{
					CoroutineRunner.Instance.StartCoroutine(settings.ShowLabelWithAnimationDelayd(promoParameters.startGold, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("gold", promoParameters.startGold), false));
				}
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				dictionary.Add("Offer", inAppProduct.idItems);
				FlurryWrapper.LogEvent(FlurryWrapper.EV_SPECIAL_OFFER_SALES, dictionary);
			}
			else
			{
				if (inAppProduct.coinsId == MoneyType.Cash)
				{
					BCWDebug.Log("add Cash " + inAppProduct.kolAddMoneySave, "InApp");
					if (!settings.offlineMode && GameController.instance != null && GameController.instance.curTypeGame == TypeGame.normal)
					{
						settings.cathedExeptionsForFlurry -= inAppProduct.kolAddMoneySave;
					}
					if (!inAppProduct.promoEnabled)
					{
						settings.ShowSpecialLabelWithAnimation(inAppProduct.kolAddMoneySave, Vector3.zero, false);
					}
					else
					{
						CoroutineRunner.Instance.StartCoroutine(settings.ShowSpecialLabelWithAnimationDelayd(inAppProduct.kolAddMoneySave, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("cash", inAppProduct.kolAddMoneySave), false));
					}
				}
				if (inAppProduct.coinsId == MoneyType.Gold)
				{
					BCWDebug.Log("add Gold " + inAppProduct.kolAddMoneySave, "InApp");
					if (!settings.offlineMode && GameController.instance != null && GameController.instance.curTypeGame == TypeGame.normal)
					{
						settings.cathedWarningstForFlurry -= inAppProduct.kolAddMoneySave;
					}
					if (!inAppProduct.promoEnabled)
					{
						settings.ShowLabelWithAnimation(inAppProduct.kolAddMoneySave, Vector3.zero, false);
					}
					else
					{
						CoroutineRunner.Instance.StartCoroutine(settings.ShowLabelWithAnimationDelayd(inAppProduct.kolAddMoneySave, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("gold", inAppProduct.kolAddMoneySave), false));
					}
				}
				if (inAppProduct.promoEnabled)
				{
					InAppPromoController.InAppPromo promoById = InAppPromoController.instance.inAppPromos.GetPromoById(inAppProduct.idItems);
					if (promoById != null)
					{
						if (!promoById.promoBonuses.GiveAlternativeBonuses())
						{
							if (promoById.promoBonuses.cashAmount > 0)
							{
								CoroutineRunner.Instance.StartCoroutine(settings.ShowSpecialLabelWithAnimationDelayd(promoById.promoBonuses.cashAmount, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("cash", promoById.promoBonuses.cashAmount), false));
							}
							if (promoById.promoBonuses.goldAmount > 0)
							{
								CoroutineRunner.Instance.StartCoroutine(settings.ShowLabelWithAnimationDelayd(promoById.promoBonuses.goldAmount, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("gold", promoById.promoBonuses.goldAmount), false));
							}
							promoById.promoBonuses.GetPromoMarketBonusesIds().ForEach(delegate(string productId)
							{
								InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI(productId, 0);
								MarketController.Instance.BuyProduct(productId, true);
							});
						}
						else
						{
							if (promoById.promoBonuses.сashAmountAlternative > 0)
							{
								CoroutineRunner.Instance.StartCoroutine(settings.ShowSpecialLabelWithAnimationDelayd(promoById.promoBonuses.сashAmountAlternative, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("cash", promoById.promoBonuses.сashAmountAlternative), false));
							}
							if (promoById.promoBonuses.goldAmountAlternative > 0)
							{
								CoroutineRunner.Instance.StartCoroutine(settings.ShowLabelWithAnimationDelayd(promoById.promoBonuses.goldAmountAlternative, InAppShopUI.instance.promoRewardCotrollerUI.SetRewardUI("gold", promoById.promoBonuses.goldAmountAlternative), false));
							}
						}
						BCWStorage.Set(promoById.uniqueKey, true);
						Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
						dictionary2.Add("Offer", inAppProduct.idItems);
						FlurryWrapper.LogEvent(FlurryWrapper.EV_SPECIAL_OFFER_SALES, dictionary2);
					}
				}
				settings.SaveCathedExeptionsToStorager();
				if (inAppProduct.chest != null && inAppProduct.chest.purchaseInfo != null)
				{
					ChestBonusController.TryTakeChestBonus(inAppProduct.chest.purchaseInfo);
				}
				playSoundBuyCoins();
			}
			UpdateGamerType(idProduct);
			DisablelIndictator();
			RefreshProducts();
		}
		else
		{
			BCWDebug.Log("Wait Loading InAppShopUI", "InApp");
			StartCoroutine(WaitLoadingInAppUI(idProduct, token));
			UpdateGamerType(idProduct);
		}
	}

	private IEnumerator WaitLoadingInAppUI(string idProduct, string token = "")
	{
		while (InAppShopUI.instance == null)
		{
			yield return new WaitForSeconds(0.5f);
		}
		productWithIdBuySuccessful(idProduct, token);
	}

	public void BlockCheaters(InAppProduct curProduct, string token = "")
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		string empty = string.Empty;
		float num = 0f;
		string text = string.Empty;
		if (_savedPurchase != null)
		{
			text = _savedPurchase.orderId;
		}
		empty = text;
		num = curProduct.dollarPrice;
		_savedPurchase = null;
		Save.SaveInt(settings.keyDonateCashOnLevel, curProduct.kolAddMoneySave);
		Save.SaveString(settings.keyLastPaymentDate, DateTimeOffset.UtcNow.ToString("s"));
		float num2 = 0f;
		num2 = Load.LoadFloat(settings.keyAllPayments);
		num2 += curProduct.packPriceForFlurry;
		Save.SaveFloat(settings.keyAllPayments, num2);
		dictionary.Clear();
		dictionary.Add("Total", curProduct.packNameForFlurry);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_PAYMENT_DISTRIBUTION, dictionary);
		dictionary.Clear();
		dictionary.Add("Day of 1st currency purchase", PromoActionManager.CurrentUnixTimeDay(PromoActionManager.CurrentUnixTimeSecond - PlayerPrefs.GetInt(settings.keyTimeStartNewUser)).ToString());
		FlurryWrapper.LogEvent(FlurryWrapper.EV_DAILY_CURRENCY_STATS, dictionary);
		dictionary.Clear();
		dictionary.Add("Total by devices", SystemInfo.deviceModel);
		dictionary.Add("Total by operation system", SystemInfo.operatingSystem);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_PAYMENT_BY_IOS_DEVICES, dictionary);
		if (!Load.LoadBool(settings.keyPayment))
		{
			dictionary.Clear();
			dictionary.Add("Total by level", CupsManager.CurrentTier.ToString());
			dictionary.Add("Purchase type Total", curProduct.packNameForFlurry);
			FlurryWrapper.LogEvent(FlurryWrapper.EV_NEW_PAYING_PLAYERS, dictionary);
		}
		dictionary.Clear();
		dictionary.Add("Total", FlurryWrapper.GetCurrentGameMode());
		dictionary.Add("Total packs", curProduct.packNameForFlurry);
		dictionary.Add(FlurryWrapper.GetCurrentGameMode(), curProduct.packNameForFlurry);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_CURENCY_PAYMENT_ON_GAME_MODE, dictionary);
		if (BCWServer.instance == null)
		{
			BCWDebug.Log("instance NULL");
			BCWServer.Init();
		}
		StartCoroutine(BCWServer.instance.SendPaying(num, empty));
		switch (curProduct.coinsId)
		{
		case MoneyType.Cash:
			dictionary.Clear();
			dictionary.Add("Cash", FlurryWrapper.GetCurrentGameMode());
			FlurryWrapper.LogEvent(FlurryWrapper.EV_CURENCY_PAYMENT_ON_GAME_MODE, dictionary);
			if (!Load.LoadBool(settings.keyPayment))
			{
				Save.SaveBool(settings.KeyFirsPurchasedCash, true);
			}
			Save.SaveInt(settings.keyBuyingCash, Load.LoadInt(settings.keyBuyingCash) + (int)curProduct.kolAddMoneySave);
			break;
		case MoneyType.Gold:
			dictionary.Clear();
			dictionary.Add("Gold", FlurryWrapper.GetCurrentGameMode());
			FlurryWrapper.LogEvent(FlurryWrapper.EV_CURENCY_PAYMENT_ON_GAME_MODE, dictionary);
			if (!Load.LoadBool(settings.keyPayment))
			{
				Save.SaveBool(settings.KeyFirsPurchasedGold, true);
			}
			Save.SaveInt(settings.keyBuyingGold, Load.LoadInt(settings.keyBuyingGold) + (int)curProduct.kolAddMoneySave);
			break;
		}
		Save.SaveBool(settings.keyPayment, true);
	}

	private void InitShop()
	{
		BCWDebug.Log("InitShop", "InApp");
		arrKeyProducts.Clear();
		if (Application.platform == RuntimePlatform.OSXEditor)
		{
			arrKeyProducts.AddRange(starterPackIAPs_iOS.Select((iapInfo x) => x.id));
			arrKeyProducts.AddRange(accountVipIAPs_iOS.Select((iapInfo x) => x.id));
			ManagerVip.GetInstance().InitConfig(accountVipDays, accountVipIAPs_iOS);
		}
		else if (Application.platform == RuntimePlatform.IPhonePlayer)
		{
			arrKeyProducts.AddRange(starterPackIAPs_iOS.Select((iapInfo x) => x.id));
			arrKeyProducts.AddRange(accountVipIAPs_iOS.Select((iapInfo x) => x.id));
			ManagerVip.GetInstance().InitConfig(accountVipDays, accountVipIAPs_iOS);
		}
		else if (Application.platform == RuntimePlatform.Android)
		{
			arrKeyProducts.AddRange(starterPackIAPs_Android.Select((iapInfo x) => x.id));
			arrKeyProducts.AddRange(accountVipIAPs_Android.Select((iapInfo x) => x.id));
			ManagerVip.GetInstance().InitConfig(accountVipDays, accountVipIAPs_Android);
		}
		if (InAppShopUI.instance != null)
		{
			foreach (InAppProduct listProduct in InAppShopUI.instance.listProducts)
			{
				if (Application.platform == RuntimePlatform.OSXEditor)
				{
					arrKeyProducts.Add(listProduct.IdItemsIOS);
				}
				if (Application.platform == RuntimePlatform.IPhonePlayer)
				{
					arrKeyProducts.Add(listProduct.IdItemsIOS);
					BCWDebug.Log("curProduct.IdItemsIOS " + listProduct.IdItemsIOS, "InApp");
				}
				if (Application.platform == RuntimePlatform.Android)
				{
					arrKeyProducts.Add(listProduct.IdItemsAndroid);
				}
				listProduct.promoEnabled = InAppPromoController.instance.inAppPromos.GetPromoById(listProduct.idItems) != null;
			}
		}
		BCWDebug.Log(" ********************** iaps");
		foreach (string arrKeyProduct in arrKeyProducts)
		{
			BCWDebug.Log(" iap name: " + arrKeyProduct);
		}
		BCWDebug.Log("**********************");
		BCWDebug.Log(" arrKeyProducts count: " + arrKeyProducts.Count, "InApp");
	}

	public void playSoundBuyCoins()
	{
	}

	public void DisablelIndictator()
	{
		ActivityIndicator.activEnabled = false;
		RefreshProducts();
	}

	public string ConverctCurrency(string keyInApp)
	{
		if (dictProductCurrency.ContainsKey(keyInApp))
		{
			BCWDebug.LogError(keyInApp + " price " + dictProductCurrency[keyInApp], "TESTING");
			return dictProductCurrency[keyInApp].price + " " + dictProductCurrency[keyInApp].code;
		}
		BCWDebug.LogError("NULL STRING", "TESTING");
		return string.Empty;
	}

	public float GetCurrencyPrice(string keyInApp)
	{
		if (dictProductCurrency.ContainsKey(keyInApp))
		{
			BCWDebug.LogError(keyInApp + " price " + dictProductCurrency[keyInApp], "TESTING");
			return dictProductCurrency[keyInApp].price;
		}
		return 0f;
	}

	public string GetCurrencyCode(string keyInApp)
	{
		if (dictProductCurrency.ContainsKey(keyInApp))
		{
			BCWDebug.LogError(keyInApp + " price " + dictProductCurrency[keyInApp], "TESTING");
			return dictProductCurrency[keyInApp].code;
		}
		return string.Empty;
	}

	private void AddCurrency(string keyInApp, float price, string currencyCode)
	{
		if (!dictProductCurrency.ContainsKey(keyInApp))
		{
			string text = ScriptLocalization.Get("Lobby_ShopCoins/currency_code_" + currencyCode);
			InAppCurrency value = default(InAppCurrency);
			value.code = ((!(text == string.Empty)) ? text : currencyCode);
			value.price = price;
			BCWDebug.LogError("price    " + price + "  localizaion  " + text, "TESTING");
			dictProductCurrency.Add(keyInApp, value);
		}
	}

	private void billingSupportedEvent()
	{
		BCWDebug.Log("billingSupportedEvent");
		GoogleIAB.queryInventory(arrKeyProducts.ToArray());
	}

	private void billingNotSupportedEvent(string error)
	{
		BCWDebug.LogWarning("billingNotSupportedEvent: " + error);
	}

	private void queryInventorySucceededEvent(List<GooglePurchase> purchases, List<GoogleSkuInfo> skus)
	{
		_products = skus.Select((GoogleSkuInfo sku) => sku.productId).ToArray();
		string arg = string.Join(", ", _products);
		string[] value = purchases.Select((GooglePurchase p) => p.productId).ToArray();
		string arg2 = string.Join(", ", value);
		string message = string.Format("queryInventorySucceededEvent;    Purchases: [{0}], Skus: [{1}]", arg2, arg);
		BCWDebug.Log(message);
		foreach (GoogleSkuInfo sku in skus)
		{
			BCWDebug.LogError(" name id " + sku.productId + "  PriceCode  " + sku.priceCurrencyCode + " price " + sku.priceAmountMicros + " price " + sku.price, "TESTING");
			AddCurrency(sku.productId, sku.priceAmountMicros / 1000000, sku.priceCurrencyCode);
		}
		foreach (GooglePurchase purchase in purchases)
		{
			_productsToConsume.Add(purchase.productId);
		}
		if (_productsToConsume.Any())
		{
			GoogleIAB.consumeProduct(_productsToConsume.First());
		}
		RefreshProducts();
	}

	private void queryInventoryFailedEvent(string error)
	{
		BCWDebug.LogWarning("Google: queryInventoryFailedEvent: " + error);
	}

	private void purchaseCompleteAwaitingVerificationEvent(string purchaseData, string signature)
	{
		BCWDebug.Log("purchaseCompleteAwaitingVerificationEvent. purchaseData: " + purchaseData + ", signature: " + signature);
	}

	private void purchaseSucceededEvent(GooglePurchase purchase)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		BCWDebug.Log("Google: purchaseSucceededEvent: " + purchase);
		if (purchase.developerPayload != purchaseProductPayload)
		{
			BCWStorage.Set("isCheater", true);
			BCWDebug.Log("Payload does not match");
			dictionary.Add("In-app purchases cheating", "Try cheat");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_CHEATING, dictionary);
			return;
		}
		if (!VerifyPurchase(purchase.originalJson, purchase.signature, "<RSAKeyValue><Modulus>qsXnLbQdmJI/MvDCtO+Z6/uvUMDfjFzlMfRE5O2o53p4QMEBSmKs3T9OW/5tta2BMHMlt4f2r6uj7KJYh93lgdkSjDMSDsk+ryG6865wsSukASUQamzXS0VFZjBwLqK9qTW6TS8KdeMLNGxQmgK4WQqV0+b+oW4n2T6UoCnX7JQegeCgtEt0mrg0cPk4kW1bfPKr11V2lPfnjBepUIpX9GSoPGXuYPAHVfxVDp0d9N3fhv8eLjhVMvM3kpr4hYD4gWxBkOQDkZ+m2jJFi/zdUehKyTqLvwm4PAPL1wL3GAkb3dfAh3ZgeflQ2ZbB8JEDy3/QK+4aveV/DbRPVTFVVw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"))
		{
			BCWDebug.Log("Wrong signature");
			BCWStorage.Set("isCheater", true);
			dictionary.Add("In-app purchases cheating", "Try cheat");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_CHEATING, dictionary);
			return;
		}
		_savedPurchase = purchase;
		productWithIdBuySuccessful(purchase.productId, string.Empty);
		InAppProduct inAppProduct = InAppShopUI.instance.listProducts.Find((InAppProduct p) => p.idItems.Equals(purchase.productId));
		if (inAppProduct != null)
		{
			BlockCheaters(inAppProduct, string.Empty);
		}
		dictionary.Add("In-app purchases cheating", "Good guy");
		FlurryWrapper.LogEvent(FlurryWrapper.EV_CHEATING, dictionary);
		GoogleIAB.consumeProduct(purchase.productId);
	}

	public static bool VerifyPurchase(string purchaseJson, string base64Signature, string xmlPublicKey)
	{
		using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider())
		{
			try
			{
				rSACryptoServiceProvider.FromXmlString(xmlPublicKey);
				byte[] signature = Convert.FromBase64String(base64Signature);
				SHA1Managed halg = new SHA1Managed();
				byte[] bytes = Encoding.UTF8.GetBytes(purchaseJson);
				return rSACryptoServiceProvider.VerifyData(bytes, halg, signature);
			}
			catch (Exception message)
			{
				BCWDebug.Log(message);
			}
			return false;
		}
	}

	private void purchaseFailedEvent(string error, int i)
	{
		BCWDebug.LogWarning("purchaseFailedEvent: " + error + ", " + i);
		DisablelIndictator();
		StarterPacksManager.instance.UnsecessfulPurchaseStarterPackIAP(string.Empty);
		if (_productsToConsume.Any() && _consumeFailureCount < 8)
		{
			GoogleIAB.consumeProduct(_productsToConsume.Last());
		}
	}

	private void consumePurchaseSucceededEvent(GooglePurchase purchase)
	{
		BCWDebug.Log("consumePurchaseSucceededEvent: " + purchase);
		_productsToConsume.Remove(purchase.productId);
		if (_productsToConsume.Any())
		{
			GoogleIAB.consumeProduct(_productsToConsume.First());
		}
		else
		{
			_consumeFailureCount = 0;
		}
	}

	private void consumePurchaseFailedEvent(string error)
	{
		BCWDebug.LogWarning("consumePurchaseFailedEvent: " + error);
		_consumeFailureCount++;
		if (_productsToConsume.Any() && _consumeFailureCount < 8)
		{
			GoogleIAB.consumeProduct(_productsToConsume.Last());
		}
	}

	private void initiateItemDataRequest()
	{
		BCWDebug.Log("InAppShop initiateItemDataRequest", "Amazon");
		AmazonIAPV2Manager.instance.InitiatePurchase(arrKeyProducts);
	}

	private void amazonGetUserDataResponse(GetUserDataResponse arg)
	{
	}

	private void amazonPurchaseResponse(PurchaseResponse arg)
	{
		if (arg.Status.ToLower().Equals(AmazonIAPV2Manager.successful.ToLower()))
		{
			productWithIdBuySuccessful(arg.PurchaseReceipt.Sku, arg.PurchaseReceipt.ReceiptId);
			AmazonIAPV2Manager.instance.NotifyFulfillment(arg.PurchaseReceipt.ReceiptId);
			BCWDebug.Log("Amazon: purchaseResponseSuccessful  " + arg.ToString(), "Amazon");
		}
		else
		{
			BCWDebug.Log("Amazon: purchaseResponseFailed  " + arg.ToString(), "Amazon");
		}
	}

	private void amazonGetProductDataResponse(GetProductDataResponse arg)
	{
		if (arg.Status.ToLower().Equals(AmazonIAPV2Manager.successful.ToLower()))
		{
			BCWDebug.Log("Amazon: amazonGetProductDataResponse Successful  " + arg.ToString(), "Amazon");
			Dictionary<string, ProductData> productDataMap = arg.ProductDataMap;
			List<string> unavailableSkus = arg.UnavailableSkus;
			_products = new string[productDataMap.Count];
			int num = 0;
			foreach (KeyValuePair<string, ProductData> item in productDataMap)
			{
				_products[num] = item.Value.Sku;
				num++;
				BCWDebug.Log(item.Value.Sku);
			}
			RefreshProducts();
			ActivityIndicator.activEnabled = false;
		}
		else
		{
			BCWDebug.Log("Amazon: amazonGetProductDataResponse Failed  " + arg.ToString(), "Amazon");
		}
	}

	private void amazonGetPurchaseUpdatesResponse(GetPurchaseUpdatesResponse arg)
	{
		if (arg.Status.ToLower().Equals(AmazonIAPV2Manager.successful.ToLower()))
		{
			List<PurchaseReceipt> receipts = arg.Receipts;
			foreach (PurchaseReceipt item in receipts)
			{
				BCWDebug.Log("Failed Buying   ", "InApp");
				BCWDebug.Log(item.Sku + "     " + item.ReceiptId, "Amazon");
				productWithIdBuySuccessful(item.Sku, item.ReceiptId);
				AmazonIAPV2Manager.instance.NotifyFulfillment(item.ReceiptId);
			}
			BCWDebug.Log("amazonGetPurchaseUpdatesResponse Successful", "Amazon");
		}
		else
		{
			BCWDebug.Log("amazonGetPurchaseUpdatesResponse Failed", "Amazon");
		}
	}
}
